// pages/profile/personal-center.ts
import { MerchantAPI } from '../../utils/api'

interface PersonalInfo {
  userId?: number | string;
  userName?: string;
  nickName?: string;
  phonenumber?: string;
  email?: string;
  sex?: string;
  sexName?: string;
  avatar?: string;
}

interface PersonalCenterData {
  statusBarHeight: number;
  personalInfo: PersonalInfo;
  loading: boolean;
}

Page({
  data: {
    statusBarHeight: 0,
    personalInfo: {} as PersonalInfo,
    loading: false
  } as PersonalCenterData,

  onLoad() {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight || 0
    });
    this.loadPersonalInfo();
  },

  onShow() {
    this.loadPersonalInfo();
  },

  async loadPersonalInfo() {
    const cached = wx.getStorageSync('merchantPersonalInfo');
    if (cached) {
      this.setData({
        personalInfo: cached
      });
    }

    this.setData({ loading: true });
    try {
      const response = await MerchantAPI.getPersonalInfo();
      if (response.code === 200 && response.data) {
        this.setData({
          personalInfo: response.data
        });
        wx.setStorageSync('merchantPersonalInfo', response.data);
      }
    } catch (error) {
      console.error('加载个人信息失败:', error);
    } finally {
      this.setData({ loading: false });
    }
  },

  refreshMerchantInfo() {
    this.loadPersonalInfo();
  },

  goBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  editProfile() {
    wx.navigateTo({
      url: '/pages/profile/edit-profile'
    });
  },

  chooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0];

        wx.showLoading({
          title: '上传中...',
          mask: true
        });

        try {
          const uploadRes = await MerchantAPI.uploadAvatar(tempFilePath);
          if (uploadRes.code === 200) {
            const avatarUrl = uploadRes.data?.avatar || uploadRes.data?.avatarUrl || uploadRes.avatar || uploadRes.avatarUrl || '';
            wx.showToast({
              title: '头像更新成功',
              icon: 'success'
            });

            // 更新缓存中的头像
            const cached = wx.getStorageSync('merchantPersonalInfo') || {};
            if (avatarUrl) {
              cached.avatar = avatarUrl;
              wx.setStorageSync('merchantPersonalInfo', cached);
            }

            // 重新加载个人信息
            setTimeout(() => {
              this.loadPersonalInfo();
            }, 500);
          } else {
            wx.showToast({
              title: uploadRes.msg || '上传失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('上传头像失败:', error);
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        } finally {
          wx.hideLoading();
        }
      }
    });
  }
});



